// services/payment.service.js
const crypto = require('crypto');
const { WechatPay } = require('wechatpay-node-v3');
const AlipaySdk = require('alipay-sdk').default;
const { logInfo, logError, logWarning } = require('../logger');

// 数据模型
const PaymentOrder = require('../models/PaymentOrder');
const Subscription = require('../models/Subscription');
const SubscriptionPlan = require('../models/SubscriptionPlan');
const { User, UserSubscription } = require('../models/User');

class PaymentService {
  constructor() {
    // 初始化微信支付
    this.wechatPay = new WechatPay({
      appid: process.env.WECHAT_APP_ID,
      mchid: process.env.WECHAT_MCH_ID,
      publicKey: process.env.WECHAT_PUBLIC_KEY_PATH,
      privateKey: process.env.WECHAT_PRIVATE_KEY_PATH,
    });

    // 初始化支付宝
    this.alipay = new AlipaySdk({
      appId: process.env.ALIPAY_APP_ID,
      gateway: process.env.ALIPAY_GATEWAY || 'https://openapi.alipay.com/gateway.do',
      privateKey: process.env.ALIPAY_PRIVATE_KEY,
      alipayPublicKey: process.env.ALIPAY_PUBLIC_KEY,
    });
  }

  /**
   * 创建支付订单
   * @param {Object} orderData - 订单数据
   * @param {string} orderData.userId - 用户ID
   * @param {string} orderData.planId - 订阅计划ID
   * @param {number} orderData.amount - 金额（分）
   * @param {string} orderData.paymentMethod - 支付方式 ('wechat' | 'alipay')
   * @returns {Object} 支付订单对象
   */
  async createPaymentOrder(orderData) {
    try {
      const { userId, planId, amount, paymentMethod } = orderData;

      // 创建订单ID
      const orderId = this.generateOrderId();

      // 创建支付订单记录
      const paymentOrder = {
        id: orderId,
        userId,
        planId,
        amount,
        status: 'pending',
        paymentMethod,
        createdAt: new Date(),
        updatedAt: new Date()
      };

      // 保存到数据库
      await this.savePaymentOrder(paymentOrder);

      logInfo('支付订单创建成功', { orderId, userId, amount, paymentMethod });
      return paymentOrder;
    } catch (error) {
      logError('创建支付订单失败', { error: error.message, stack: error.stack });
      throw new Error('创建支付订单失败');
    }
  }

  /**
   * 生成订单ID
   * @returns {string} 订单ID
   */
  generateOrderId() {
    // 生成唯一订单ID：时间戳+随机数
    return `ORDER_${Date.now()}_${Math.random().toString(36).substr(2, 9).toUpperCase()}`;
  }

  /**
   * 保存支付订单到数据库
   * @param {PaymentOrder} paymentOrder - 支付订单对象
   */
  async savePaymentOrder(paymentOrder) {
    return await PaymentOrder.create(paymentOrder);
  }

  /**
   * 获取支付订单
   * @param {string} orderId - 订单ID
   * @returns {PaymentOrder|null} 支付订单对象
   */
  async getPaymentOrder(orderId) {
    try {
      const order = await PaymentOrder.findOne({ where: { orderId } });
      return order ? order.toJSON() : null;
    } catch (error) {
      logError('获取支付订单失败', { orderId, error: error.message });
      throw new Error('获取支付订单失败');
    }
  }

  /**
   * 更新支付订单状态
   * @param {string} orderId - 订单ID
   * @param {string} status - 状态
   * @param {Object} transactionData - 交易数据
   */
  async updatePaymentOrderStatus(orderId, status, transactionData = {}) {
    try {
      await PaymentOrder.update({
        status: status,
        transactionId: transactionData.transactionId || null,
        metadata: transactionData,
        updatedAt: new Date()
      }, {
        where: {
          orderId: orderId
        }
      });

      logInfo('支付订单状态更新成功', { orderId, status });
    } catch (error) {
      logError('更新支付订单状态失败', { orderId, status, error: error.message });
      throw new Error('更新支付订单状态失败');
    }
  }

  /**
   * 处理微信支付回调
   * @param {Object} notification - 回调通知数据
   * @returns {Object} 处理结果
   */
  async handleWechatPayCallback(notification) {
    try {
      // 验证签名
      const isValid = this.wechatPay.verifySign(notification);
      if (!isValid) {
        logWarning('微信支付回调签名验证失败', { notification });
        throw new Error('签名验证失败');
      }

      // 获取订单信息
      const orderId = notification.resource.original.out_trade_no;
      const paymentOrder = await this.getPaymentOrder(orderId);

      if (!paymentOrder) {
        logWarning('微信支付回调订单不存在', { orderId });
        throw new Error('订单不存在');
      }

      // 检查订单状态
      if (paymentOrder.status === 'completed') {
        logInfo('微信支付回调订单已处理', { orderId });
        return { success: true, message: '订单已处理' };
      }

      // 更新订单状态
      await this.updatePaymentOrderStatus(orderId, 'completed', {
        transactionId: notification.resource.original.transaction_id,
        payerInfo: notification.resource.original.payer
      });

      // 创建订阅
      await this.createSubscriptionForOrder(paymentOrder);

      logInfo('微信支付回调处理成功', { orderId });
      return { success: true, message: '支付成功' };
    } catch (error) {
      logError('处理微信支付回调失败', { error: error.message, stack: error.stack });
      throw new Error('处理支付回调失败');
    }
  }

  /**
   * 处理支付宝回调
   * @param {Object} params - 回调参数
   * @returns {Object} 处理结果
   */
  async handleAlipayCallback(params) {
    try {
      // 验证签名
      const isValid = this.alipay.checkNotifySign(params);
      if (!isValid) {
        logWarning('支付宝回调签名验证失败', { params });
        throw new Error('签名验证失败');
      }

      // 获取订单信息
      const orderId = params.out_trade_no;
      const paymentOrder = await this.getPaymentOrder(orderId);

      if (!paymentOrder) {
        logWarning('支付宝回调订单不存在', { orderId });
        throw new Error('订单不存在');
      }

      // 检查订单状态
      if (paymentOrder.status === 'completed') {
        logInfo('支付宝回调订单已处理', { orderId });
        return { success: true, message: '订单已处理' };
      }

      // 检查支付状态
      if (params.trade_status !== 'TRADE_SUCCESS') {
        logWarning('支付宝回调支付状态不成功', { orderId, tradeStatus: params.trade_status });
        throw new Error('支付未成功');
      }

      // 更新订单状态
      await this.updatePaymentOrderStatus(orderId, 'completed', {
        transactionId: params.trade_no,
        payerInfo: {
          buyerId: params.buyer_id,
          buyerLogonId: params.buyer_logon_id
        }
      });

      // 创建订阅
      await this.createSubscriptionForOrder(paymentOrder);

      logInfo('支付宝回调处理成功', { orderId });
      return { success: true, message: '支付成功' };
    } catch (error) {
      logError('处理支付宝回调失败', { error: error.message, stack: error.stack });
      throw new Error('处理支付回调失败');
    }
  }

  /**
   * 为订单创建订阅
   * @param {PaymentOrder} paymentOrder - 支付订单
   */
  async createSubscriptionForOrder(paymentOrder) {
    try {
      // 获取订阅计划
      const plan = await this.getSubscriptionPlan(paymentOrder.planId);
      if (!plan) {
        throw new Error('订阅计划不存在');
      }

      // 计算订阅时间
      const startDate = new Date();
      const endDate = new Date(startDate);
      endDate.setDate(startDate.getDate() + plan.durationDays);

      // 创建订阅记录
      const subscription = {
        id: `SUB_${Date.now()}_${Math.random().toString(36).substr(2, 9).toUpperCase()}`,
        userId: paymentOrder.userId,
        planId: paymentOrder.planId,
        status: 'active',
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString(),
        autoRenew: true, // 默认自动续订
        transactionId: paymentOrder.id,
        createdAt: new Date(),
        updatedAt: new Date()
      };

      // 保存订阅到数据库
      await this.saveSubscription(subscription);

      // 更新用户VIP状态
      await this.updateUserVipStatus(paymentOrder.userId, true, endDate);

      logInfo('订阅创建成功', { subscriptionId: subscription.id, userId: paymentOrder.userId });
    } catch (error) {
      logError('为订单创建订阅失败', { 
        orderId: paymentOrder.id, 
        userId: paymentOrder.userId, 
        error: error.message 
      });
      throw new Error('创建订阅失败');
    }
  }

  /**
   * 获取订阅计划
   * @param {string} planId - 计划ID
   * @returns {SubscriptionPlan|null} 订阅计划对象
   */
  async getSubscriptionPlan(planId) {
    try {
      // 首先尝试从数据库获取订阅计划
      let plan = await SubscriptionPlan.findOne({ where: { id: planId } });
      
      // 如果数据库中没有订阅计划，则创建默认计划
      if (!plan) {
        const defaultPlans = [
          { id: 'monthly', name: 'monthly', displayName: '月度会员', price: 1800, currency: 'CNY', durationDays: 30, features: [], isPopular: false },
          { id: 'quarterly', name: 'quarterly', displayName: '季度会员', price: 4800, currency: 'CNY', durationDays: 90, features: [], isPopular: false },
          { id: 'yearly', name: 'yearly', displayName: '年度会员', price: 9800, currency: 'CNY', durationDays: 365, features: [], isPopular: true }
        ];

        // 批量创建默认订阅计划
        await SubscriptionPlan.bulkCreate(defaultPlans, { ignoreDuplicates: true });
        
        // 再次查询
        plan = await SubscriptionPlan.findOne({ where: { id: planId } });
      }

      return plan ? plan.toJSON() : null;
    } catch (error) {
      logError('获取订阅计划失败', { planId, error: error.message });
      throw new Error('获取订阅计划失败');
    }
  }

  /**
   * 保存订阅到数据库
   * @param {Subscription} subscription - 订阅对象
   */
  async saveSubscription(subscription) {
    return await UserSubscription.create(subscription);
  }

  /**
   * 查询支付状态
   * @param {string} orderId - 订单ID
   * @returns {Object} 支付状态信息
   */
  async getPaymentStatus(orderId) {
    try {
      const paymentOrder = await this.getPaymentOrder(orderId);
      if (!paymentOrder) {
        throw new Error('订单不存在');
      }

      return {
        orderId: paymentOrder.id,
        status: paymentOrder.status,
        amount: paymentOrder.amount,
        paymentMethod: paymentOrder.paymentMethod,
        createdAt: paymentOrder.createdAt,
        updatedAt: paymentOrder.updatedAt
      };
    } catch (error) {
      logError('查询支付状态失败', { orderId, error: error.message });
      throw new Error('查询支付状态失败');
    }
  }

  /**
   * 更新用户VIP状态
   * @param {string} userId - 用户ID
   * @param {boolean} isVip - 是否为VIP
   * @param {Date} vipExpiresAt - VIP过期时间
   */
  async updateUserVipStatus(userId, isVip, vipExpiresAt) {
    try {
      await User.update(
        {
          isVip: isVip,
          vipExpiresAt: vipExpiresAt
        },
        {
          where: { id: userId }
        }
      );
      
      logInfo('用户VIP状态更新成功', { userId, isVip, vipExpiresAt });
    } catch (error) {
      logError('更新用户VIP状态失败', { userId, error: error.message });
      throw new Error('更新用户VIP状态失败');
    }
  }
}

module.exports = PaymentService;